from django import forms
from web import models
from utils.form_placeholder import form_placeholder
from django.core.exceptions import ValidationError


class add_edit(form_placeholder, forms.ModelForm):
    class Meta:
        model = models.Wiki
        exclude = ['project', 'depth']

    def __init__(self, request, *args, **kwargs):
        super(add_edit, self).__init__(*args, **kwargs)
        self.request = request
        # 重写字段
        data_list = [('', '--请选择--')]
        model_list = models.Wiki.objects.filter(project=self.request.tracer.project).values_list('id', 'title')
        data_list.extend(model_list)
        self.fields['parent'].choices = data_list

    # 当前项目是否有当前文章标题
    def clean_title(self):
        title = self.cleaned_data.get('title')
        exist = models.Wiki.objects.filter(project=self.request.tracer.project, title=title).exists()
        if exist:
            raise ValidationError('当前项目已有该名称')
        if '2b' in title:
            raise ValidationError('当前题目含有违背社会主义青年的词汇')
        return title
